﻿#region << 版 本 注 释 >>
/*----------------------------------------------------------------
 * 创建者：王明亮
 * 创建时间：2023/8/24 15:48:27
 * 版本：V1.0.0
 * 描述：
 *
 * ----------------------------------------------------------------
 * 修改人：
 * 时间：
 * 修改说明：
 *
 * 版本：V1.0.1
 *----------------------------------------------------------------*/
#endregion << 版 本 注 释 >>
using Microsoft.AspNetCore.SignalR;
using SignalRApi.Hubs;

namespace SignalRApi.Jobs
{
    /// <summary>
    /// 定义定时任务
    /// </summary>
    public class MyWorker
    {
        /// <summary>
        /// 单例
        /// </summary>
        public static MyWorker Instance;
        /// <summary>
        /// 锁
        /// </summary>
        private static readonly object locker = new object();
        /// <summary>
        /// 集线器请求上下文
        /// </summary>
        private IHubContext<MyHub> context;
        /// <summary>
        /// 定时器
        /// </summary>
        public static System.Timers.Timer timer;

        /// <summary>
        /// 构造注入
        /// </summary>
        /// <param name="context"></param>
        public MyWorker(IHubContext<MyHub> context)
        {
            this.context = context;
            timer = new System.Timers.Timer(1000);//单位毫秒
            timer.Enabled = true;
            timer.AutoReset = true;//自动重新
            timer.Elapsed += Timer_Elapsed;
            timer.Start();
        }

        /// <summary>
        /// 时钟到达事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Timer_Elapsed(object? sender, System.Timers.ElapsedEventArgs e)
        {
            //模拟数据，一般情况下，从数据库获取，然后通知到客户端
            Dictionary<string, object> data = new Dictionary<string, object>();
            var online = new Random().Next(0, 100);
            var male = Math.Floor(new Random().NextSingle() * online);
            var female = online - male;
            data["online"] = online;
            data["male"] = male;
            data["female"] = female;
            context.Clients.All.SendAsync("Data", data);
        }

        /// <summary>
        /// 单例注册服务
        /// </summary>
        /// <param name="context"></param>
        public static void Register(IHubContext<MyHub> context)
        {
            if (Instance == null)
            {
                lock (locker)
                {
                    if (Instance == null)
                    {
                        Instance = new MyWorker(context);
                    }
                }
            }
        }
    }
}
